package com.chj.leetcode.tijie0to50;

//https://blog.csdn.net/qq_25406563/article/details/83934161
//https://blog.csdn.net/weixin_43166958/article/details/106297463
//https://leetcode-cn.com/problems/reverse-integer/solution/tu-wen-xiang-jie-javadai-ma-de-2chong-shi-xian-fan/
public class Code7_ReverseInteger {
	public int reverse(int x) {
		long res = 0;
		while (x != 0) {
			res = res * 10 + x % 10;
			x = x / 10;
		}
		if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
			return 0;
		}
		return (int) res;
	}

	public int reverse02(int x) {
		boolean neg = false;
		if (x < 0) {
			neg = true;
			x = -x;
		}
		long res = 0L;
		int tmp = 0;
		while (x != 0) {
			tmp = x % 10;
			x /= 10;
			res = res * 10 + tmp;
		}
		if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
			res = 0;
		if (neg == true)
			res = -res;
		return (int) res;
	}

	public int reverse03(int x) {
		boolean tag = false; // 记录x正负
		if (x == Integer.MIN_VALUE)// 如果x为最小值 即-2147483648时，那么其Math.abs（x）求绝对值的结果与该值相同且为负。
			return 0;
		if (x < 0) { // 如果x为负数的话，取其绝对值
			tag = true;
			x = Math.abs(x);
		}
		String tmp = Integer.toString(x); // 将x转化为对应的字符串
		String res = new StringBuilder(tmp).reverse().toString(); // 将字符串翻转
		long result = Long.parseLong(res); // 将字符串转换为long
		if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) // 反转后数值溢出
			return 0;
		if (tag == true) // 还原负数
			result = -result;
		return (int) result;
	}

	public static void reverseString(char[] s) {
		int l = 0;
		int r = s.length - 1;
		reverse(s, l, r);
	}

	public static void reverse(char[] chs, int l, int r) {
		while (l < r) {
			char tmp = chs[l];
			chs[l++] = chs[r];
			chs[r--] = tmp;
		}
	}

	public int reverse04(int x) {

		boolean tag = false; // 记录x正负
		if (x == Integer.MIN_VALUE)// 如果x为最小值 即-2147483648时，那么其Math.abs（x）求绝对值的结果与该值相同且为负。
			return 0;
		if (x < 0) { // 如果x为负数的话，取其绝对值
			tag = true;
			x = Math.abs(x);
		}

		char[] tmp = Integer.toString(x).toCharArray(); // 将x转化为对应的字符串
		reverseString(tmp);
		long result = Long.parseLong(String.valueOf(tmp)); // 将字符串转换为long
		if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) // 反转后数值溢出
			return 0;
		if (tag == true) // 还原负数
			result = -result;
		return (int) result;
	}
}
